package com.cool.config.springsecurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.Objects;

/**
 * 访问决策管理器
 *
 * @author Jiangmanman
 * @date 2020/07/27
 */
@Slf4j
public class AccessDecisionManager implements org.springframework.security.access.AccessDecisionManager {

    /**
     * 不需要做权限的URL
     *
     * @date 2020/07/27
     * @see String[]
     */
    private String[] urls;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public AccessDecisionManager(){
        urls = new String[]{};
    }

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        FilterInvocation filterInvocation = (FilterInvocation) object;
        for (String str:urls){
            if(antPathMatcher.match(str,filterInvocation.getRequestUrl())){
                //通过
                return;
            }
        }
        //判断是否登录
        if(authentication instanceof AnonymousAuthenticationToken){
            throw new AccessDeniedException("账户未登录");
        }
//        if(!Objects.isNull(collection) && collection.size() ==1 && "login".equals(collection.iterator().next())){
//            //当用户只需要一个登录权限的时间,就直接通过
//            return;
//        }
        for(ConfigAttribute configuration:collection){

            String needAuthority = configuration.getAttribute();

            for(GrantedAuthority grantedAuthority:authentication.getAuthorities()){

                if(Objects.equals(needAuthority,grantedAuthority.getAuthority())){
                    return;
                }

            }

        }
        log.info("collection: "+collection);
        log.info("authentication.getAuthorities(): "+authentication.getAuthorities());
        throw new AccessDeniedException("没有访问权限");


    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
